import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import gameService from '../services/gameService';

// 卡牌数值枚举牌型枚举
export enum HandRank {
  HIGH_CARD = 'High Card',
  PAIR = 'Pair',
  TWO_PAIR = 'Two Pair',
  THREE_OF_A_KIND = 'Three of a Kind',
  STRAIGHT = 'Straight',
  FLUSH = 'Flush',
  FULL_HOUSE = 'Full House',
  FOUR_OF_A_KIND = 'Four of a Kind',
  STRAIGHT_FLUSH = 'Straight Flush',
  ROYAL_FLUSH = 'Royal Flush',
}

// 牌面值枚举
export enum CardValue {
  TWO = 2,
  THREE = 3,
  FOUR = 4,
  FIVE = 5,
  SIX = 6,
  SEVEN = 7,
  EIGHT = 8,
  NINE = 9,
  TEN = 10,
  JACK = 11,
  QUEEN = 12,
  KING = 13,
  ACE = 14,
}

// 牌花色枚举
export enum CardSuit {
  CLUBS = 'Clubs',
  DIAMONDS = 'Diamonds',
  HEARTS = 'Hearts',
  SPADES = 'Spades',
}

// 卡牌接口
export interface Card {
  value: CardValue;
  suit: CardSuit;
}

// 玩家接口
export interface Player {
  id: string;
  username: string;
  chips: number;
  cards: Card[];
  currentBet: number;
  hasFolded: boolean;
  isAllIn: boolean;
  position: number;
}

// 游戏阶段枚举
export enum GamePhase {
  WAITING = 'Waiting',
  PREFLOP = 'Pre-Flop',
  FLOP = 'Flop',
  TURN = 'Turn',
  RIVER = 'River',
  SHOWDOWN = 'Showdown',
}

// 游戏状态接口
export interface GameState {
  id: string;
  name: string;
  players: Player[];
  communityCards: Card[];
  pot: number;
  currentBet: number;
  dealerPosition: number;
  currentPlayerPosition: number;
  phase: GamePhase;
  isStarted: boolean;
  minBet: number;
  maxPlayers: number;
}

// 游戏大厅中的游戏信息
export interface GameInfo {
  id: string;
  name: string;
  playerCount: number;
  maxPlayers: number;
  minBet: number;
  status: 'waiting' | 'in-progress' | 'finished';
}

// 游戏状态
interface GameSliceState {
  currentGame: GameState | null;
  availableGames: GameInfo[];
  isLoading: boolean;
  error: string | null;
  isPlayerTurn: boolean;
  playerActions: {
    canCheck: boolean;
    canCall: boolean;
    canRaise: boolean;
    canFold: boolean;
    canAllIn: boolean;
  };
}

// 初始状态
const initialState: GameSliceState = {
  currentGame: null,
  availableGames: [],
  isLoading: false,
  error: null,
  isPlayerTurn: false,
  playerActions: {
    canCheck: false,
    canCall: false,
    canRaise: false,
    canFold: false,
    canAllIn: false,
  },
};

// 创建游戏切片
const gameSlice = createSlice({
  name: 'game',
  initialState,
  reducers: {
    setCurrentGame: (state, action: PayloadAction<GameState>) => {
      state.currentGame = action.payload;
    },
    setAvailableGames: (state, action: PayloadAction<GameInfo[]>) => {
      state.availableGames = action.payload;
    },
    addPlayerToGame: (state, action: PayloadAction<Player>) => {
      if (state.currentGame) {
        state.currentGame.players.push(action.payload);
      }
    },
    removePlayerFromGame: (state, action: PayloadAction<string>) => {
      if (state.currentGame) {
        state.currentGame.players = state.currentGame.players.filter(
          player => player.id !== action.payload
        );
      }
    },
    updatePlayerChips: (state, action: PayloadAction<{ playerId: string; chips: number }>) => {
      if (state.currentGame) {
        const player = state.currentGame.players.find(p => p.id === action.payload.playerId);
        if (player) {
          player.chips = action.payload.chips;
        }
      }
    },
    setCommunityCards: (state, action: PayloadAction<Card[]>) => {
      if (state.currentGame) {
        state.currentGame.communityCards = action.payload;
      }
    },
    updateGamePhase: (state, action: PayloadAction<GamePhase>) => {
      if (state.currentGame) {
        state.currentGame.phase = action.payload;
      }
    },
    updatePot: (state, action: PayloadAction<number>) => {
      if (state.currentGame) {
        state.currentGame.pot = action.payload;
      }
    },
    updateCurrentBet: (state, action: PayloadAction<number>) => {
      if (state.currentGame) {
        state.currentGame.currentBet = action.payload;
      }
    },
    setCurrentPlayerPosition: (state, action: PayloadAction<number>) => {
      if (state.currentGame) {
        state.currentGame.currentPlayerPosition = action.payload;
      }
    },
    setIsPlayerTurn: (state, action: PayloadAction<boolean>) => {
      state.isPlayerTurn = action.payload;
    },
    updatePlayerActions: (state, action: PayloadAction<Partial<typeof initialState.playerActions>>) => {
      state.playerActions = { ...state.playerActions, ...action.payload };
    },
    clearError: (state) => {
      state.error = null;
    },
    setError: (state, action: PayloadAction<string>) => {
      state.error = action.payload;
    },
    resetGame: (state) => {
      state.currentGame = null;
      state.isPlayerTurn = false;
      state.playerActions = initialState.playerActions;
    },
  },
});

export const {
  setCurrentGame,
  setAvailableGames,
  addPlayerToGame,
  removePlayerFromGame,
  updatePlayerChips,
  setCommunityCards,
  updateGamePhase,
  updatePot,
  updateCurrentBet,
  setCurrentPlayerPosition,
  setIsPlayerTurn,
  updatePlayerActions,
  clearError,
  setError,
  resetGame,
} = gameSlice.actions;

// 创建一个异步动作来处理游戏动作
export const makeGameAction = (gameId: string, action: {
  type: 'check' | 'call' | 'raise' | 'fold' | 'all-in';
  amount?: number;
}) => async (dispatch: any) => {
  try {
    // 调用游戏服务API
    const gameState = await gameService.makeGameAction(gameId, action);
    
    // 更新游戏状态
    dispatch(setCurrentGame(gameState));
    
    // 更新玩家动作权限
    const currentUserId = localStorage.getItem('userId');
    if (currentUserId && gameState.players) {
      const currentPlayer = gameState.players.find((p: Player) => p.id === currentUserId);
      const isPlayerTurn = gameState.currentPlayerPosition === currentPlayer?.position;
      
      dispatch(setIsPlayerTurn(isPlayerTurn));
      
      // 根据游戏状态更新玩家可用动作
      if (isPlayerTurn && currentPlayer) {
        const canCheck = gameState.currentBet === currentPlayer.currentBet;
        const canCall = gameState.currentBet > currentPlayer.currentBet && currentPlayer.chips > 0;
        const canRaise = currentPlayer.chips > 0;
        const canFold = !currentPlayer.hasFolded;
        const canAllIn = currentPlayer.chips > 0;
        
        dispatch(updatePlayerActions({
          canCheck,
          canCall,
          canRaise,
          canFold,
          canAllIn,
        }));
      } else {
        dispatch(updatePlayerActions({
          canCheck: false,
          canCall: false,
          canRaise: false,
          canFold: false,
          canAllIn: false,
        }));
      }
    }
    
    return { success: true };
  } catch (error) {
    console.error('Game action failed:', error);
    // 恢复玩家回合状态
    dispatch(setIsPlayerTurn(true));
    dispatch(setError('游戏动作执行失败'));
    return { success: false, error };
  }
};

export default gameSlice.reducer;